package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.pojo.OrderDetail;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import javafx.scene.control.Label;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: hamo
 * @Create by: 渭北彭于晏
 * @Date: 2021/11/7 14:47
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 支付
     * @param orders
     * @return
     */
    @PostMapping("/submit")
public R submit(@RequestBody Orders orders){
    orderService.submit(orders);
    return R.success("好家伙");
}

    /**
     * 历史订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R page(Integer page,Integer pageSize){
    IPage<Orders> ipage = new Page<>(page,pageSize);
    LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
    wrapper.orderByAsc(Orders::getCheckoutTime);
    IPage<Orders> result = orderService.page(ipage,wrapper);//分页查询

    List<Orders> list = result.getRecords();//获取页面数据

    List<Orders> dtoList = list.stream().map((order) -> {
        OrdersDto dto = new OrdersDto();
        BeanUtils.copyProperties(order, dto);//拷贝订单
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId, order.getId());
        List<OrderDetail> orderDetails = orderDetailService.list(lqw);
        dto.setOrderDetails(orderDetails);//添加订单明细
        return dto;
    }).collect(Collectors.toList());

    result.setRecords(dtoList);//覆盖分页数据

    return R.success(result);
}
}